package com.xbongbong.pay.platform.unionpay.utils;

import com.xbongbong.pay.platform.unionpay.config.UnionPayMeta;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.KeyPair;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.Enumeration;

public class UnionPayCertUtil {
    private static final Logger LOG = LoggerFactory.getLogger(UnionPayCertUtil.class);


    /**
     * 根据配置的证书生成 配置元数据
     * @author 魏荣杰
     * @date 2021/1/22 10:38
     * @since
     * @version
     */
    public static UnionPayMeta createUnionPayMeta(String keyPath, String keyType, String keyPwd) {
        UnionPayMeta unionPayMeta = new UnionPayMeta();
        ClassPathResource resource = new ClassPathResource(keyPath);
        char[] pem = keyPwd.toCharArray();
        try {
            KeyStore store = KeyStore.getInstance(keyType);
            store.load(resource.getInputStream(), pem);
            X509Certificate certificate = (X509Certificate) store.getCertificate(keyType);
            certificate.checkValidity();
            String serialNumber = certificate.getSerialNumber().toString(16).toUpperCase();
            PublicKey publicKey = certificate.getPublicKey();
            PrivateKey privateKey = (PrivateKey) store.getKey(keyType, pem);
            unionPayMeta.setKeyStore(store);
            unionPayMeta.setSerialNumber(serialNumber);
            unionPayMeta.setKeyPair(new KeyPair(publicKey, privateKey));
//            unionPayMeta.setCertificate(certificate);
        } catch (Exception e) {
            LOG.error("Cannot load keys from store: " + resource, e);
        }
        return unionPayMeta;
    }


    public static String getSignCertId(KeyStore keyStore) {
        try {
            Enumeration<String> aliases = keyStore.aliases();
            String keyAlias = null;
            if (aliases.hasMoreElements()) {
                keyAlias = aliases.nextElement();
            }
            X509Certificate cert = (X509Certificate) keyStore
                    .getCertificate(keyAlias);
            return cert.getSerialNumber().toString();
        } catch (Exception e) {
            return null;
        }

    }

    public static PrivateKey getSignCertPrivateKey(KeyStore keyStore, String signCertPwd ) {
        try {
            Enumeration<String> aliasenum = keyStore.aliases();
            String keyAlias = null;
            if (aliasenum.hasMoreElements()) {
                keyAlias = aliasenum.nextElement();
            }
            PrivateKey privateKey = (PrivateKey) keyStore.getKey(keyAlias, signCertPwd.toCharArray());
            return privateKey;
        } catch (KeyStoreException | NoSuchAlgorithmException | UnrecoverableKeyException e) {
            return null;
        }
    }

    /**
     * 将签名私钥证书文件读取为证书存储对象
     *
     * @param pfxkeyfile
     *            证书文件名
     * @param keypwd
     *            证书密码
     * @param type
     *            证书类型
     * @return 证书对象
     * @throws IOException
     */
    public static KeyStore getKeyStore(String pfxkeyfile, String keypwd,
                                       String type) {
        LOG.info("Load RSA CertPath=[" + pfxkeyfile + "],Pwd=["+ keypwd + "],type=["+type+"]");

        ClassPathResource resource = new ClassPathResource(pfxkeyfile);
        KeyStore ks = null;
        try {
            ks = KeyStore.getInstance(type);
            ks.load(resource.getInputStream(), keypwd.toCharArray());
        } catch (KeyStoreException | NoSuchAlgorithmException | CertificateException | IOException e) {
            LOG.error("getKeyInfo Error", e);
        }
        return ks;
    }

    /**
     * 通过证书路径初始化为公钥证书
     * @param path
     * @return
     */
    public static X509Certificate initCert(String path) {
        X509Certificate encryptCertTemp = null;
        CertificateFactory cf = null;
//        FileInputStream in = null;
        try {
//            cf = CertificateFactory.getInstance("X.509", "BC");
            cf = CertificateFactory.getInstance("X.509");
//            in = new FileInputStream(path);
            ClassPathResource resource = new ClassPathResource(path);
//            encryptCertTemp = (X509Certificate) cf.generateCertificate(in);
            encryptCertTemp = (X509Certificate) cf.generateCertificate(resource.getInputStream());
            // 打印证书加载信息,供测试阶段调试
            LOG.info("[" + path + "][CertId="
                    + encryptCertTemp.getSerialNumber().toString() + "]");
        } catch (CertificateException e) {
            LOG.error("InitCert Error", e);
        } catch (FileNotFoundException e) {
            LOG.error("InitCert Error File Not Found", e);
        }
//        catch (NoSuchProviderException e) {
//            LOG.error("LoadVerifyCert Error No BC Provider", e);
//        }
        catch (IOException e) {
            e.printStackTrace();
        } finally {
//            if (null != in) {
//                try {
//                    in.close();
//                } catch (IOException e) {
//                    LOG.error(e.toString());
//                }
//            }
        }
        return encryptCertTemp;
    }
}
